package com.phiture.erp.stock.core.service.impl;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import com.phiture.erp.stock.core.pojo.dto.ErpStockRecordCreateReqDTO;
import com.phiture.erp.stock.core.pojo.dto.ErpStockRecordPageReqDTO;
import com.phiture.erp.stock.core.service.ErpStockRecordService;
import com.phiture.erp.stock.core.service.ErpStockService;
import com.phiture.erp.stock.dal.entity.ErpStockRecordDO;
import com.phiture.erp.stock.dal.mapper.ErpStockRecordMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.phiture.erp.common.constants.ErrorCodeConstants.PRODUCE_IN_STOCK_NO_EXISTS;

/**
 * ERP 物料库存明细 Service 实现类
 */
@Service
@RequiredArgsConstructor
public class ErpStockRecordServiceImpl implements ErpStockRecordService {
    private final ErpStockRecordMapper stockRecordMapper;
    private final ErpStockService stockService;

    @Override
    public ErpStockRecordDO getStockRecord(Long id) {
        return stockRecordMapper.selectById(id);
    }

    @Override
    public PageResult<ErpStockRecordDO> getStockRecordPage(ErpStockRecordPageReqDTO pageReqDTO) {
        return stockRecordMapper.selectPage(pageReqDTO, new LambdaQueryWrapperX<ErpStockRecordDO>()
                .eqIfPresent(ErpStockRecordDO::getMaterialId, pageReqDTO.getMaterialId())
                .eqIfPresent(ErpStockRecordDO::getWarehouseId, pageReqDTO.getWarehouseId())
                .eqIfPresent(ErpStockRecordDO::getBizType, pageReqDTO.getBizType())
                .likeIfPresent(ErpStockRecordDO::getBizNo, pageReqDTO.getBizNo())
                .betweenIfPresent(ErpStockRecordDO::getCreateTime, pageReqDTO.getCreateTime())
                .orderByDesc(ErpStockRecordDO::getId));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void createStockRecord(ErpStockRecordCreateReqDTO createReqDTO) {
        // 如果仓库ID为空，抛出异常
        if (createReqDTO.getWarehouseId() == null) {
            throw exception(PRODUCE_IN_STOCK_NO_EXISTS);
        }
        // 1. 更新库存
        BigDecimal totalCount = stockService.updateStockCountIncrement(
                createReqDTO.getMaterialId(), createReqDTO.getWarehouseId(), createReqDTO.getCount());
        // 2. 创建库存明细
        ErpStockRecordDO stockRecord = BeanUtils.toBean(createReqDTO, ErpStockRecordDO.class)
                .setTotalCount(totalCount);
        stockRecordMapper.insert(stockRecord);
    }

}